package com.katze.boot.plugins.shiro.authentication;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.katze.boot.plugins.redis.exception.TokenTimeoutException;
import com.katze.boot.plugins.redis.service.CacheService;
import com.katze.boot.system.domain.User;
import com.katze.boot.system.service.UserService;
import com.katze.common.http.HttpUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.pam.UnsupportedTokenException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 自定义实现 ShiroRealm，包含认证和授权两大模块
 *
 * @author MrBird
 */
public class ShiroRealm extends AuthorizingRealm {

    @Lazy
    @Autowired
    private UserService userService;
    @Lazy
    @Autowired
    private CacheService cacheService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    /**
     * 用户认证
     *
     * @param authenticationToken 身份认证 token
     * @return AuthenticationInfo 身份认证信息
     * @throws AuthenticationException 认证相关异常
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 这里的 token是从 JWTFilter 的 executeLogin 方法传递过来的，已经经过了解密
        String token = (String) authenticationToken.getCredentials();
        String username = JWTUtils.getUsername(token);
        String tokenCache = cacheService.getToken(username);
        // 如果找不到，说明已经失效或被强制下线
        if (StringUtils.isBlank(tokenCache)){
            throw new TokenTimeoutException("Token不存在");
        } else {
            HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
            if (!HttpUtils.getRemoteAddress(request).equals(tokenCache.split("@")[1])){
                throw new UnsupportedTokenException("Token绑定IP与当前访问IP不符");
            }
        }

        // 通过用户名查询用户信息
        User user = userService.findCacheByName(username);

        if (user == null){
            throw new UnknownAccountException("用户不存在");
        }
        if (!this.verify(token, user)){
            throw new AuthenticationException("Token校验失败");
        }
        return new SimpleAuthenticationInfo(token, token, "febs_shiro_realm");
    }


    /**`
     * 授权模块，获取用户角色和权限
     *
     * @param token token
     * @return AuthorizationInfo 权限信息
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection token) {
        String username = JWTUtils.getUsername(token.toString());
        // 通过用户名查询用户信息
        User user = userService.findCacheByName(username);

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

        // 获取用户角色集
        simpleAuthorizationInfo.setRoles(user.getRoles());

        // 获取用户权限集
        simpleAuthorizationInfo.setStringPermissions(user.getPermissions());
        return simpleAuthorizationInfo;
    }


    /**
     * 校验 token是否正确
     *
     * @param token  密钥
     * @param user 用户
     * @return 是否正确
     */
    private boolean verify(String token, User user) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(user.getPassword());
            JWTVerifier verifier = JWT.require(algorithm)
                    .withClaim("id", user.getUserId())
                    .withClaim("username", user.getUsername())
                    .build();
            verifier.verify(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
